package flc.ast.activity;

import android.content.Context;
import android.graphics.Color;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.CountDownTimer;
import android.os.Handler;
import android.view.View;


import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import flc.ast.BaseAc;
import flc.ast.R;
import flc.ast.bean.ResultBean;
import flc.ast.databinding.ActivityGuessBinding;
import stark.common.basic.utils.TimeUtil;

public class GuessActivity extends BaseAc<ActivityGuessBinding> implements SensorEventListener {

    public static int type;
    public static int time;
    private boolean isPrepare = false;//是否准备
    private boolean isStart = false;//是否开始
    private boolean isShow = true;//是否显示
    private List<String> listWord = new ArrayList<>();//词语列表
    private List<ResultBean> listResult = new ArrayList<>();//结果列表
    private int tmpPos = -1;
    private SensorManager sensorManager;
    private Sensor accelerometerSensor;
    private int number;

    @Override
    protected int onCreate() {
        return R.layout.activity_guess;
    }

    @Override
    protected void initView() {
        mDataBinding.tvGuessExit.setOnClickListener(this);
        mDataBinding.tvGuessStart.setOnClickListener(this);
        mDataBinding.rlGuessPlaying.setOnClickListener(this);

        sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
        accelerometerSensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.tvGuessExit://退出
                goResult();
                break;
            case R.id.tvGuessStart://开始
                prepareNumber();
                break;
            case R.id.rlGuessPlaying:
                if (isShow) return;
                isShow = true;
                mDataBinding.llGuessMenu.setVisibility(View.VISIBLE);
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        isShow = false;
                        mDataBinding.llGuessMenu.setVisibility(View.GONE);
                    }
                }, 3000);
                break;
        }
    }

    @Override
    protected void initData() {
        String json = loadJSONFromAsset(mContext);
        try {
            JSONObject jsonObject = new JSONObject(json);
            JSONArray jsonArray = jsonObject.getJSONArray("list");
            JSONObject jsonObject1 = jsonArray.getJSONObject(type);
            JSONArray jsonArray1 = jsonObject1.getJSONArray("wordList");
            for (int i = 0; i < jsonArray1.length(); i++) {
                listWord.add(jsonArray1.getString(i));
            }
            Collections.shuffle(listWord);
        } catch (JSONException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        sensorManager.registerListener(this, accelerometerSensor, SensorManager.SENSOR_DELAY_NORMAL);
    }

    // 设置中间显示的数据
    private void setContent() {
        if (tmpPos == listWord.size() - 1) {
           goResult();
           return;
        }
        tmpPos++;
        mDataBinding.tvGuessWord.setText(listWord.get(tmpPos));
        listResult.add(new ResultBean(listWord.get(tmpPos), false));
    }

    private void goResult() {
        ResultActivity.listResult = listResult;
        startActivity(ResultActivity.class);
        finish();
    }

    private void prepareNumber() {
        mDataBinding.rlGuessPrepare.setVisibility(View.GONE);
        mDataBinding.rlGuessPlaying.setVisibility(View.VISIBLE);
        mDataBinding.tvGuessStart.setVisibility(View.GONE);
        isPrepare = true;
        number = 3;
        new CountDownTimer(3000, 1000) {

            @Override
            public void onTick(long millisUntilFinished) {
                //millisUntilFinished / 1000 会有不可描述的问题
                mDataBinding.tvGuessTime.setText("" + number--);
            }

            @Override
            public void onFinish() {
                isStart = true;
                isShow = false;
                mDataBinding.tvGuessMark.setVisibility(View.GONE);
                mDataBinding.llGuessTip.setVisibility(View.VISIBLE);
                mDataBinding.llGuessMenu.setVisibility(View.GONE);
                countDown();
                setContent();
            }
        }.start();
    }

    private void countDown() {
        new CountDownTimer(time * 1000, 1000) {

            @Override
            public void onTick(long millisUntilFinished) {
                mDataBinding.tvGuessTime.setText(TimeUtil.getMmss(millisUntilFinished));
            }

            @Override
            public void onFinish() {
                goResult();
            }
        }.start();
    }

    private void isRight() {
        isStart = false;
        mDataBinding.rlGuessPlaying.setBackgroundColor(Color.parseColor("#A2D41A"));
        mDataBinding.tvGuessWord.setText(getString(R.string.right));
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                isStart = true;
                mDataBinding.rlGuessPlaying.setBackgroundColor(Color.parseColor("#333333"));
                listResult.get(tmpPos).setRight(true);
                setContent();
            }
        }, 1000);
    }

    private void isSkip() {
        isStart = false;
        mDataBinding.rlGuessPlaying.setBackgroundColor(Color.parseColor("#68AEED"));
        mDataBinding.tvGuessWord.setText(getString(R.string.skip));
        mDataBinding.tvGuessMark.setVisibility(View.VISIBLE);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                isStart = true;
                mDataBinding.rlGuessPlaying.setBackgroundColor(Color.parseColor("#333333"));
                mDataBinding.tvGuessMark.setVisibility(View.GONE);
                setContent();
            }
        }, 500);
    }

    // 读取JSON文件
    public String loadJSONFromAsset(Context context) {
        String json = null;
        try {
            InputStream is = context.getAssets().open("guess.json");
            int size = is.available();
            byte[] buffer = new byte[size];
            is.read(buffer);
            is.close();
            json = new String(buffer, "UTF-8");
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        return json;
    }

    @Override
    protected void onPause() {
        super.onPause();
        sensorManager.unregisterListener(this);
    }

    @Override
    public void onSensorChanged(SensorEvent event) {
        if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
            float x = event.values[0];
            float y = event.values[1];
            float z = event.values[2];

            double magnitude = Math.sqrt(x * x + y * y + z * z);

            // Normalize the accelerometer vector
            float normX = x / (float) magnitude;
            float normY = y / (float) magnitude;
            float normZ = z / (float) magnitude;

            if (Math.abs(normX) > 0.9 || Math.abs(normY) > 0.9) {//垂直
                if (!isPrepare) {
                    prepareNumber();
                }
            }
            if (z < -9.0) { // 向下翻转
                if (isStart) {
                    isRight();
                }
            }
            if (z > 9.0) { // 向上翻转
                if (isStart) {
                    isSkip();
                }
            }
        }
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {

    }

}